<template>
  <div class="createBlog">
    <h1>{{titleName}}</h1>
    <div class="uploadImg">
      <h4>上传封面</h4>
      <el-upload
        :action="getUploadURL()"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :file-list="fileList">
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="博客封面" />
      </el-dialog>
    </div>
    <div class="title">
      <el-input v-model="Blog.title" placeholder="博客标题"></el-input>
    </div>
    <div class="mavon-editor">
      <mavon-editor
        @change="updateDoc"
        @imgAdd="imgAdd"
        ref="editor"
        v-model="Blog.md_text">
      </mavon-editor>
    </div>
    <div>
      <!-- 保存 -->
      <el-button type="success" @click="saveData">保存</el-button>
    </div>
  </div>
</template>

<script>
import { mavonEditor } from "mavon-editor";
import "mavon-editor/dist/css/index.css";
import request from "../utils/request";
export default {
  data() {
    return {
      // 博客表单
      Blog: {
        title: "",
        img: "",
        md_text: "",
        html_text: "",
      },
      // 文件列表
      fileList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      // 编辑id
      editItemID:"",
      // 是否处于编辑转态
      isEdit:false,
    };
  },
  components: {
    mavonEditor,
  },

  methods: {
    updateDoc(markdown, html) {
      // 此时会自动将 markdown 和 html 传递到这个方法中
      this.Blog.html_text = html;
    },
   async saveData() {
      if (this.Blog.title) {
        if(!this.isEdit){
         const {data:res} = await request({
            method: "post",
            url: "blog",
            data: {
              title: this.Blog.title,
              img: this.Blog.img,
              md_text: this.Blog.md_text,
              html_text: this.Blog.html_text}
         })
          if(res.code === 20000){
            this.$message.success("添加博客成功");
            this.$router.push("/blog");
          }else{
            this.$message.error("添加博客失败，请重试")
          }
        }else{
         const {data:res} = await request({
            method: "put",
            url: `blog/${this.editItemID}`,
            data: {
              title: this.Blog.title,
              img: this.Blog.img,
              md_text: this.Blog.md_text,
              html_text: this.Blog.html_text}
         })
          if(res.code === 20000){
            this.$message.success("修改博客成功");
            this.$router.push("/blog");
          }else{
            this.$message.error("修改博客失败，请重试")
          }
      }
      } else {
        this.$message.error("请输入标题");
      }
    },
    imgAdd(filename, $file) {
      let formdata = new FormData();
      formdata.append("image", $file);
      request({
        method: "post",
        url: `${process.env.VUE_APP_BASE_API}upload`,
        data: formdata,
        headers: { "Content-Tpye": "multipart/form-data" },
      }).then((res) => {
        let url = res.data.data.file;
        this.$refs.editor.$img2Url(filename, url);
      });
    },
    //获取上传连接
    getUploadURL() {
      return `${process.env.VUE_APP_BASE_API}upload`;
    },
    // 封面上传成功
    handleSuccess(response) {
      this.Blog.img = response.data.file;
      console.log(this.dialogImageUrl)
    },
    // 移除封面
    handleRemove({response}, fileList) {
      this.deleteimg(response.data.file)
    },
    // 封面预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 删除封面
    deleteimg(img){
      let arr = img.split("/")
      let target = arr[arr.length-1]
      request({
        method:"delete",
        url:`/unlink/${target}`
      })
    }
  },
  computed:{
    titleName(){
      return this.isEdit?"编辑博客":"添加博客"
    }
  },
  created() {
    if(this.$route.query.id){
      this.editItemID = this.$route.query.id;
      this.isEdit = true;
    }else{
      this.editItemID = "";
    }
  },
  async mounted() {
    if(this.isEdit){
      const {data:res} = await request.get(`/blog?id=${this.editItemID}`)
      if(res.code === 20000){
        const {title,img,md_text,html_text} = res.data;
        this.Blog.title = title;
        this.Blog.img = img;
        this.Blog.md_text = md_text;
        this.Blog.html_text = html_text;
        this.fileList = [{url:img}]
      }else{
        this.$message.error("获取博客失败");
      }
    }
  }
};
</script>